from typing import List, Optional, Dict, Any
from datetime import datetime
from models.sleep_monitoring import Room, SleepMonitoringRecord
from service.base_service import BaseService
import uuid


class RoomService(BaseService):
    """
    房间管理服务
    负责房间的创建、查询、更新和删除操作
    """
    
    def __init__(self):
        super().__init__()
        self.model = Room
    
    async def create_room(self, room_name: str, description: str = None) -> Room:
        """
        创建新房间
        
        Args:
            room_name: 房间名称
            description: 房间描述
            
        Returns:
            Room: 创建的房间对象
        """
        room_id = str(uuid.uuid4())
        
        room = Room.create(
            room_id=room_id,
            room_name=room_name,
            description=description,
            is_active=True
        )
        
        self.logger.info(f"创建房间成功: {room_id} - {room_name}")
        return room
    
    async def get_room_by_id(self, room_id: str) -> Optional[Room]:
        """
        根据房间ID获取房间信息
        
        Args:
            room_id: 房间ID
            
        Returns:
            Optional[Room]: 房间对象，如果不存在则返回None
        """
        try:
            return Room.get(Room.room_id == room_id)
        except Room.DoesNotExist:
            return None
    
    async def get_active_rooms(self) -> List[Room]:
        """
        获取所有激活的房间
        
        Returns:
            List[Room]: 激活的房间列表
        """
        return list(Room.select().where(Room.is_active == True))
    
    async def get_all_rooms(self) -> List[Room]:
        """
        获取所有房间
        
        Returns:
            List[Room]: 所有房间列表
        """
        return list(Room.select())
    
    async def update_room(self, room_id: str, **kwargs) -> Optional[Room]:
        """
        更新房间信息
        
        Args:
            room_id: 房间ID
            **kwargs: 要更新的字段
            
        Returns:
            Optional[Room]: 更新后的房间对象
        """
        room = await self.get_room_by_id(room_id)
        if not room:
            return None
        
        # 更新允许的字段
        allowed_fields = ['room_name', 'description', 'is_active']
        for field, value in kwargs.items():
            if field in allowed_fields:
                setattr(room, field, value)
        
        room.updated_at = datetime.now()
        room.save()
        
        self.logger.info(f"更新房间成功: {room_id}")
        return room
    
    async def deactivate_room(self, room_id: str) -> bool:
        """
        停用房间
        
        Args:
            room_id: 房间ID
            
        Returns:
            bool: 是否成功停用
        """
        room = await self.get_room_by_id(room_id)
        if not room:
            return False
        
        room.is_active = False
        room.updated_at = datetime.now()
        room.save()
        
        self.logger.info(f"停用房间成功: {room_id}")
        return True
    
    async def activate_room(self, room_id: str) -> bool:
        """
        激活房间
        
        Args:
            room_id: 房间ID
            
        Returns:
            bool: 是否成功激活
        """
        room = await self.get_room_by_id(room_id)
        if not room:
            return False
        
        room.is_active = True
        room.updated_at = datetime.now()
        room.save()
        
        self.logger.info(f"激活房间成功: {room_id}")
        return True
    
    async def delete_room(self, room_id: str) -> bool:
        """
        删除房间（物理删除）
        注意：只有在没有关联数据时才能删除
        
        Args:
            room_id: 房间ID
            
        Returns:
            bool: 是否成功删除
        """
        room = await self.get_room_by_id(room_id)
        if not room:
            return False
        
        # 检查是否有关联的监测记录
        has_records = SleepMonitoringRecord.select().where(
            SleepMonitoringRecord.room_id == room_id
        ).exists()
        
        if has_records:
            self.logger.warning(f"房间 {room_id} 有关联数据，无法删除")
            return False
        
        room.delete_instance()
        self.logger.info(f"删除房间成功: {room_id}")
        return True
    
    async def get_room_statistics(self, room_id: str) -> Dict[str, Any]:
        """
        获取房间统计信息
        
        Args:
            room_id: 房间ID
            
        Returns:
            Dict[str, Any]: 房间统计信息
        """
        room = await self.get_room_by_id(room_id)
        if not room:
            return {}
        
        # 统计监测记录数量
        total_sessions = SleepMonitoringRecord.select().where(
            SleepMonitoringRecord.room_id == room_id
        ).count()
        
        # 统计最近30天的会话数
        from datetime import timedelta
        thirty_days_ago = datetime.now() - timedelta(days=30)
        recent_sessions = SleepMonitoringRecord.select().where(
            (SleepMonitoringRecord.room_id == room_id) &
            (SleepMonitoringRecord.start_time >= thirty_days_ago)
        ).count()
        
        # 获取最后一次监测时间
        last_session = SleepMonitoringRecord.select().where(
            SleepMonitoringRecord.room_id == room_id
        ).order_by(SleepMonitoringRecord.start_time.desc()).first()
        
        last_monitoring_time = None
        if last_session:
            last_monitoring_time = last_session.start_time
        
        return {
            'room_id': room_id,
            'room_name': room.room_name,
            'is_active': room.is_active,
            'total_sessions': total_sessions,
            'recent_sessions_30d': recent_sessions,
            'last_monitoring_time': last_monitoring_time,
            'created_at': room.created_at,
            'updated_at': room.updated_at
        }
    
    async def search_rooms(self, keyword: str) -> List[Room]:
        """
        搜索房间
        
        Args:
            keyword: 搜索关键词
            
        Returns:
            List[Room]: 匹配的房间列表
        """
        return list(Room.select().where(
            (Room.room_name.contains(keyword)) |
            (Room.description.contains(keyword))
        ))
    
    async def validate_room_access(self, room_id: str) -> bool:
        """
        验证房间访问权限
        
        Args:
            room_id: 房间ID
            
        Returns:
            bool: 是否有访问权限
        """
        room = await self.get_room_by_id(room_id)
        return room is not None and room.is_active